package geektime.io.nio;

import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.SocketChannel;
import java.util.concurrent.Callable;

/**
 * 处理请求的处理器
 */
public class RequestHandleProcessor implements Callable {

    private SelectionKey key;

    public RequestHandleProcessor(SelectionKey key) {
        this.key = key;
    }

    @Override
    public Object call() throws Exception {
        ByteBuffer buffer = ByteBuffer.allocate(1024);
        SocketChannel socketChannel = (SocketChannel)key.channel();
        // 将socketChannel中的数据读取到buffer，并返回读取结果
        int count = socketChannel.read(buffer);
        if (count < 0) {
            // 取消所有channel和这个key进行注册的关系，返回时key将被置为无效键的集合中。在下一次selection操作时，这个key将被移除
            key.cancel();
            socketChannel.close();
            System.out.println("Received invalid data, close the connection.");
            return null;
        } else if (count == 0) {
            return null;
        }
        System.out.println("Thread->" + Thread.currentThread().getName() + "->Received data: " + new String(buffer.array()));
        // 老师没有关闭socketChannel，为什么呢？
        socketChannel.close();
        return null;
    }
}
